package cn.turing.firecontrol.admin.rest;

import cn.turing.firecontrol.admin.biz.UploadBiz;
import cn.turing.firecontrol.admin.config.AjaxResult;
import cn.turing.firecontrol.admin.entity.BackChunk;
import cn.turing.firecontrol.admin.entity.BackFilelist;
import cn.turing.firecontrol.common.exception.base.BusinessException;
import cn.turing.firecontrol.common.exception.base.ParamErrorException;
import cn.turing.firecontrol.common.msg.ObjectRestResponse;
import cn.turing.firecontrol.common.util.UUIDUtils;
import cn.turing.firecontrol.common.util.UploadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

//@Controller
//@RequestMapping("upload")
@Api("文件管理")
@RestController
@RequestMapping("/file")
public class UploadController {

    @Autowired
    private UploadBiz uploadBiz;

    /**
     * 上传文件
     */
    @ApiOperation("上传文件")
    @PostMapping("/upload")
    public AjaxResult postFileUpload(@ModelAttribute BackChunk chunk, HttpServletResponse response)
    {
        int i = uploadBiz.postFileUpload(chunk, response);
        return toAjax(i);
    }

    /**
     * 检查文件上传状态
     */
    @ApiOperation("合并文件")
    @PostMapping("/merge")
    public AjaxResult merge(BackFilelist fileInfo)
    {
        int i = uploadBiz.mergeFile(fileInfo);
        /*if(i == CommonConstant.UPDATE_EXISTS.intValue()){
            //应对合并时断线导致的无法重新申请合并的问题
            return new AjaxResult(200,"已合并,无需再次提交");
        }*/
        return toAjax(i);
    }

    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    protected AjaxResult toAjax(int rows)
    {
        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
    }



//    @PostMapping("qiniu")
//    @ResponseBody
    public ObjectRestResponse<String> qiNiu(MultipartFile file){
        if(file == null || file.isEmpty()){
            throw new ParamErrorException("文件不能为空");
        }
        String originalFilename = file.getOriginalFilename();
        Integer index = originalFilename.lastIndexOf(".");
        String key = UUIDUtils.generateShortUuid();
        if(index>0){
            key += originalFilename.substring(index);
        }
        try {
            Map<String,String> map = UploadUtil.simpleupload(file.getBytes(),key);
            String url = map.get("url");
            return new ObjectRestResponse<String>().data(url);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException(e.getMessage());
        }
    }



}
